/*
 * http://code.google.com/p/anttesttools/
 * 使用java -jar *.jar 方式运行程序时，获得*.jar文件所在的位置
 */
package anttesttools.tools;

import java.io.File;
import java.net.URI;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author anttesttools
 */
public class JarPath
{
    private static Logger log = LoggerFactory.getLogger(JarPath.class);

    /**
     * 正常的jar文件
     * 
     * @return
     */
    public static String getPath()
    {
        String path = null;
        try
        {
            URL jarPath_URL = new JarPath().getClass().getProtectionDomain().getCodeSource().getLocation();
            URI jarPath_URI = jarPath_URL.toURI();
            File jarPath = new File(jarPath_URI);
            path = jarPath.getParent() + "/";
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return path;
    }

    /**
     * One-Jar方式打包的jar文件
     * 
     * @return
     */
    public static String getOneJarPath()
    {
        String path = null;
        try
        {
            URL jarPath_URL = new JarPath().getClass().getProtectionDomain().getCodeSource().getLocation();
            // URI jarPath_URI = jarPath_URL.toURI();
            URI jarPath_URI = new URI(jarPath_URL.getFile().split("!")[0]);
            // log.debug("{}", jarPath_URI);
            File jarPath = new File(jarPath_URI);
            path = jarPath.getParent() + "/";
            // log.debug("{}", path);
        }
        catch (Exception e)
        {
            log.error("{}", e);
        }
        return path;
    }

    public static void main(String[] args)
    {
        System.out.println(getPath());
        System.out.println(getOneJarPath());
    }
}
